<template>
    <div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="ruleForm.idNumber"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="$router.push({ name: 'Employee' })">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script>
  import { addEmployee, getEmployeeById, editEmployee } from "@/api/employee";
  export default {
    created() {
      if (this.isEdit) {
        getEmployeeById(this.$route.query.id).then((res) => {
          this.ruleForm = res.data; 
        });
      }
    },
    data() {
      return {
        ruleForm: {
          username: "",
          name: "",
          phone: "",
          sex: "1",
          idNumber: "",
        },
        rules: {
          username: [{ required: true, message: "请输入账号", trigger: "blur" }],
          name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
          phone: [
            { required: true, message: "请输入手机号", trigger: "blur" },
            { min: 11, max: 11, message: "长度需符合规定", trigger: "blur" },
          ],
          sex: [{ required: true, message: "请选择性别", trigger: "change" }],
          idNumber: [
            { required: true, message: "请填写身份证号", trigger: "blur" },
            { min: 18, max: 18, message: "长度需符合规定", trigger: "blur" },
          ],
        },
      };
    },
    computed: {
      isEdit() {
        return this.$route.query.isEdit;
      },
    },
    methods: {
      handleSave() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            if (this.isEdit) {
              await editEmployee(this.ruleForm);
            } else {
              await addEmployee(this.ruleForm);
            }
            this.$message.success("保存成功");
            this.$router.push({ name: "Employee" });
          } else {
            return false;
          }
        });
      },
    },
  };
  </script>
  
  <style>
  .el-form {
    width: 500px;
  }
  </style>
  